const fs = require('fs')
//引入第三方库
//下载网页内容的库
const request = require('syncrequest')
//数据转化树状dom
const cheerio = require('cheerio')

class Movie {
    constructor() {
        this.name = ''
    }
}

const fromDiv = (div) => {
    let e = cheerio.load(div)
    let m = new Movie
    m.name = e('.title').text()
    return m
}

const fromUrl = (url) => {
    let xml = request.get.sync(url)
    let body = xml.body
    let e = cheerio.load(body)
    let movieDatas = e('li')
    let result = []
    for (i = 0; i < movieDatas.length; i++) {
        let div = movieDatas[i]
        let movies = fromDiv(div)
        result.push(movies)
    }
    return result
}

const ensurePath = () => {
    let path = './mock'
    if (!fs.existsSync(path)) {
        fs.mkdirSync('./mock')
    }
}

const saveMovie = (data) => {
    ensurePath()
    fs.writeFileSync('./mock/douban.json', data, (err, data) => {
        if (err) {
            console.log(err)
        } else {
            console.log('success')
        }
    })
}

const main = () => {
    //1.下载网页
    //2提取内容
    let url = 'https://movie.douban.com/top250?start=0&filter='
    let movie = fromUrl(url)
    let data = JSON.stringify(movie, null, 2)
    saveMovie(data)
}

main()
